package com.zy.web.servlet;

import com.zy.pojo.Employee;
import com.zy.pojo.ResultInfo;
import com.zy.service.EmployeeService;
import com.zy.service.impl.EmployeeServiceImpl;
import com.zy.util.GenerateCodeUtils;
import com.zy.web.servlet.base.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2021/6/2
 * Time: 下午 13:58
 * Description: 登录servlet
 */
@WebServlet("/login/*")
public class LoginServlet extends BaseServlet {

    private EmployeeService employeeService = new EmployeeServiceImpl();

    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute("employee");
        ResultInfo resultInfo = new ResultInfo(200, "退出成功", null);
        writeValue(resultInfo, response);
    }

    /**
     * 职工登录
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void employee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        System.out.println(name);
        System.out.println(password);
        Employee resultEmployee = employeeService.getEmployeeByNameAndPassword(name, password);
        ResultInfo resultInfo = new ResultInfo();
        if (resultEmployee == null) {
            resultInfo.setCode(404);
            resultInfo.setMessage("用户不存在，请联系管理员");
            resultInfo.setData(null);
            writeValue(resultInfo, response);
            return;
        }
        if ("用户名或密码错误".equals(resultEmployee.getName())) {
            resultInfo.setCode(400);
            resultInfo.setMessage(resultEmployee.getName());
            resultInfo.setData(null);
            writeValue(resultInfo, response);
            return;
        }
        resultInfo.setCode(200);
        resultInfo.setMessage("登录成功");
        resultEmployee.setPassword("");
        request.getSession().setAttribute("employee", resultEmployee);
        System.out.println(resultEmployee);
        resultInfo.setData(resultEmployee);
        writeValue(resultInfo, response);


    }

    /**
     * 登录发送验证码
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void code(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        GenerateCodeUtils generateCodeUtils = new GenerateCodeUtils();
        Integer code = generateCodeUtils.generateCode(99999, 10000);
        ResultInfo resultInfo = new ResultInfo(200, "操作成功", code);
        writeValue(resultInfo, response);
    }
}